package tech.aistar.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.aistar.pojo.Result;
import tech.aistar.pojo.User;
import tech.aistar.pojo.UserCollectionVo;
import tech.aistar.service.UserCollectionService;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringJoiner;

@RestController
@RequestMapping("collection")
public class UserCollectionController {
	@Autowired
	private UserCollectionService userCollectionService;
	
	@GetMapping
	public Result<List<UserCollectionVo>> index(HttpServletRequest request) {
		User user = (User) request.getAttribute("loginUser");
		List<UserCollectionVo> collections = userCollectionService.findByUserId(user.getId());
		return Result.success(collections);
	}
	
	// 通过id进行删除
	@DeleteMapping("{CollectionId}")
	public Result<UserCollectionVo> delId(@PathVariable("CollectionId") String CollectionId) {
		//b用来判断是否删除成功，删除成功返回success，失败返回fail
		boolean b = false;
		// 因为传输的String可能不知有数字，所以转换Integer用try catch包裹
		try {
			b = userCollectionService.delPCollectionId(Integer.parseInt(CollectionId));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		// 用 b 判断是否成功
		if (b)
			return Result.success();
		else
			return Result.fail("图片编号错误");
	}
	
	
	@DeleteMapping("/delIds/{CollectionIds}")
	public Result<UserCollectionVo> delIds(@PathVariable("CollectionIds") String collectionIds) {
		//b用来判断是否删除成功，删除成功返回success，失败返回fail
		boolean b = false;
		
		// 把string转换为list的int
		String[] strings = collectionIds.split(",");
		List<Integer> ids = new ArrayList<Integer>();
		for (String s : strings) {
			try {
				ids.add(Integer.parseInt(s));
			} catch (NumberFormatException e) {
				throw new RuntimeException(e);
			}
		}
		b = userCollectionService.delPCollectionIds(ids);
		
		// 用 b 判断是否成功
		if (b)
			return Result.success();
		else
			return Result.fail("图片编号错误");
	}
	
	
}
